﻿using System;
using System.Web.Mvc;
using Redis;
using SuperiorCommon;

namespace SuperiorShopkeeper.Controllers
{
    public class WeiXinController : BaseController
    {
        // GET: WeiXin
        public ActionResult Index()
        {
            return View();
        }
        /*
         {"Msg_Signature":"ef05f2ac29a4459408eb18b6e6f7cb4ee3b96c00","Timestamp":"1562412079","Nonce":"829512597","Token":null,"EncodingAESKey":null,"CorpId":null}
             */
        public ActionResult Authority()
        {
            return View();
        }


        public ActionResult AuthorityNotice()
        {
            var postModel = new PostModel();
            postModel.Msg_Signature = Request["Msg_Signature"];
            postModel.Timestamp = Request["Timestamp"];
            postModel.Nonce = Request["Nonce"];

            LogManger.Instance.WriteLog("获取postModel" + postModel.ToJson());
            try
            {
                var msg = InterfaceApi.Component_verify_ticket(postModel, Request.InputStream);

                if (msg.InfoType == ThirdPartyInfo.component_verify_ticket.ToString())
                {
                    LogManger.Instance.WriteLog("获取ComponentVerifyTicket" + msg.ComponentVerifyTicket);
                    //存储ticket
                    RedisManager.Set<string>("ComponentVerifyTicket", msg.ComponentVerifyTicket, DateTime.Now.AddMinutes(20));
                    //MangerComponent_token();//全网发布后就注释掉，只接受ticket
                    
                }
                else if (msg.InfoType == ThirdPartyInfo.unauthorized.ToString())
                {
                    //取消事件 
                    LogManger.Instance.WriteLog("推送取消");
                   
                }

            }
            catch (Exception ex)
            {
                LogManger.Instance.WriteLog("获取推送消息异常：" + ex.ToString());
                return Content("error");
            }
            return Content("success");
            
        }

        /// <summary>
        /// 管理第三方平台token和获取预授权码
        /// </summary>
        private void MangerComponent_token()
        {
            //先从缓存获取
            var token = RedisManager.Get<string>("Component_token");
            if (token == null)
            {
                try
                {
                    var componentVerifyTicket = RedisManager.Get<string>("ComponentVerifyTicket");
                    if (componentVerifyTicket == null)
                    {
                        LogManger.Instance.WriteLog("等待微信推送ComponentVerifyTicket");
                        return;
                    }
                    token = InterfaceApi.Component_token(componentVerifyTicket.ToString()).component_access_token;
                    //缓存1.5小时
                    RedisManager.Set<string>("Component_token", token, DateTime.Now.AddMinutes(90));
                }
                catch (Exception ex)
                {

                    LogManger.Instance.WriteLog("获取第三方平台token：" + ex.ToString());
                    return;
                }
            }
            var  _pre_auth_code = InterfaceApi.Create_preauthcode(token.ToString()).pre_auth_code;
            RedisManager.Set<string>("Pre_auth_code", _pre_auth_code, DateTime.Now.AddMinutes(10));
            //Response.Write("success");
        }

        public ActionResult CallBack()
        {
            try
            {
                var component_token = RedisManager.Get<string>("Component_token");
                if (component_token == null)
                {
                   // LogManger.Instance.WriteLog("component_token过期");
                    return Content("component_token过期");
                }
                var auth_code = Request["auth_code"];
                string expires_in = Request["expires_in"];
                LogManger.Instance.WriteLog("auth_code:" + auth_code);
                var authInfo = InterfaceApi.Query_auth(component_token.ToString(), auth_code);
                
                //授权方appid
                var authorizer_appid = authInfo.authorization_info.authorizer_appid;
                //LogManger.Instance.WriteLog("Callback authorizer_appid: " + authInfo.authorization_info.authorizer_appid);
                //GetAuth(authorizer_appid, component_token.ToString());//全网发布后注释
                var shopAppId = CookieHelper.GetCookieValue("PROGRAME_ID");
                //存储当前用户授权authorizer_access_token,2小时
                RedisManager.Set<string>("authorizer_access_token_"+shopAppId, authInfo.authorization_info.authorizer_access_token, DateTime.Now.AddMinutes(120));
                //存储当前用户得刷新令牌
                RedisManager.Set<string>("authorizer_refresh_token_" + shopAppId, authInfo.authorization_info.authorizer_refresh_token, DateTime.Now.AddYears(20));
                Response.Redirect("/ShopApp/CheckVersion?id="+shopAppId+ "&authorizer_appid="+authorizer_appid+"&act="+authInfo.authorization_info.authorizer_access_token);
                return new EmptyResult();
            }
            catch (Exception ex)
            {
                
                LogManger.Instance.WriteLog("授权回调事件 获取公众号信息出错:" + ex.ToString());
                return Content("授权回调异常");
            }

        }

        /// <summary>
        /// 获取授权帐号信息
        /// </summary>
        /// <returns></returns>
        private PublicAuthorizerUserInfo GetAuth(string authorizer_appid, string component_token)
        {
            try
            {
                var authInfo = InterfaceApi.Get_authorizer_info(component_token, authorizer_appid);
                LogManger.Instance.WriteLog("获取授权帐号信息"+authInfo.ToJson());
                return authInfo;
            }
            catch (Exception ex)
            {
                LogManger.Instance.WriteLog("获取授权帐号信息出错:" + ex.ToString());
                return null;
            }
        }
    }

   
}
